// pages/scan-pay/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    storeInfo: {
      name: '春熙路小材米',
      id: ''
    },
    amount: '',
    displayAmount: '0.00',
    memo: '',
    quickAmounts: ['10.00', '20.00', '50.00', '100.00', '200.00', '500.00'],
    inputFocus: true,
    showPayDialog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取门店信息
    if (options.storeId && options.storeName) {
      this.setData({
        storeInfo: {
          id: options.storeId,
          name: decodeURIComponent(options.storeName)
        }
      });
    }
    
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: `向${this.data.storeInfo.name}付款`
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 金额输入处理
   */
  onAmountInput(e) {
    let value = e.detail.value;
    
    // 移除非数字和小数点的字符
    value = value.replace(/[^\d.]/g, '');
    
    // 确保只有一个小数点
    const dotIndex = value.indexOf('.');
    if (dotIndex !== -1) {
      value = value.substring(0, dotIndex + 1) + value.substring(dotIndex + 1).replace(/\./g, '');
    }
    
    // 限制小数点后两位
    if (value.includes('.')) {
      const parts = value.split('.');
      if (parts[1] && parts[1].length > 2) {
        value = parts[0] + '.' + parts[1].substring(0, 2);
      }
    }
    
    // 限制最大金额
    if (parseFloat(value) > 99999) {
      value = '99999.00';
      wx.showToast({
        title: '金额不能超过99999元',
        icon: 'none'
      });
    }
    
    this.setData({
      amount: value,
      displayAmount: this.formatAmount(value)
    });
  },

  /**
   * 备注输入处理
   */
  onMemoInput(e) {
    this.setData({
      memo: e.detail.value
    });
  },

  /**
   * 选择快捷金额
   */
  selectQuickAmount(e) {
    const amount = e.currentTarget.dataset.amount;
    this.setData({
      amount: amount,
      displayAmount: this.formatAmount(amount),
      inputFocus: false
    });
  },

  /**
   * 格式化金额显示两位小数
   */
  formatAmount(amount) {
    if (!amount || amount === '') return '0.00';
    return parseFloat(amount).toFixed(2);
  },

  /**
   * 确认支付
   */
  confirmPayment() {
    const amount = parseFloat(this.data.amount);
    
    if (!amount || amount <= 0) {
      wx.showToast({
        title: '请输入正确的金额',
        icon: 'none'
      });
      return;
    }
    
    if (amount < 0.01) {
      wx.showToast({
        title: '金额不能小于0.01元',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showPayDialog: true
    });
  },

  /**
   * 取消支付
   */
  cancelPay() {
    this.setData({
      showPayDialog: false
    });
  },

  /**
   * 处理支付
   */
  processPay() {
    const that = this;
    const amount = parseFloat(this.data.amount);
    
    wx.showLoading({
      title: '支付中...'
    });
    
    // 模拟支付处理
    setTimeout(() => {
      wx.hideLoading();
      
      // 这里应该调用实际的支付API
      // 现在模拟支付成功
      that.setData({
        showPayDialog: false
      });
      
      wx.showModal({
        title: '支付成功',
        content: `已向${that.data.storeInfo.name}支付¥${amount.toFixed(2)}`,
        showCancel: false,
        confirmText: '完成',
        success: function() {
          // 支付成功后的处理
          that.savePaymentRecord(amount);
          
          // 返回上一页或跳转到成功页面
          wx.navigateBack({
            delta: 1
          });
        }
      });
    }, 2000);
    
    // 实际项目中的支付流程示例：
    /*
    wx.requestPayment({
      timeStamp: '',
      nonceStr: '',
      package: '',
      signType: 'MD5',
      paySign: '',
      success: function(res) {
        // 支付成功
        that.setData({
          showPayDialog: false
        });
        wx.showToast({
          title: '支付成功',
          icon: 'success'
        });
        that.savePaymentRecord(amount);
      },
      fail: function(res) {
        // 支付失败
        that.setData({
          showPayDialog: false
        });
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        });
      }
    });
    */
  },

  /**
   * 保存支付记录
   */
  savePaymentRecord(amount) {
    const record = {
      storeId: this.data.storeInfo.id,
      storeName: this.data.storeInfo.name,
      amount: amount,
      timestamp: Date.now(),
      status: 'success'
    };
    
    // 保存到本地存储
    let paymentRecords = wx.getStorageSync('paymentRecords') || [];
    paymentRecords.unshift(record);
    
    // 只保留最近100条记录
    if (paymentRecords.length > 100) {
      paymentRecords = paymentRecords.slice(0, 100);
    }
    
    wx.setStorageSync('paymentRecords', paymentRecords);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: `向${this.data.storeInfo.name}付款`,
      path: `/pages/scan-pay/index?storeId=${this.data.storeInfo.id}&storeName=${encodeURIComponent(this.data.storeInfo.name)}`
    };
  }
})